package com.songcy.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dao.ObjectDao;
import com.pro.bean.Unit;
import com.pro.bean.Users;
import com.songcy.dao.UnitDao;
import com.songcy.dao.UserDao;

public class GetUsersServlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("UTF-8");
		String arg = new String(request.getParameter("arg").getBytes("ISO-8859-1"),"UTF-8");
		UnitDao dao = new UnitDao();
		List units = dao.GetUintByName(arg);
		List users = null;
		if(arg.equals("all"))
		{
			out.println("([\"all\"])");
			return;
		}
		else if(arg.equals("my"))
		{
			out.println("([\"my\"])");
			return ;
		}
		else
		{
			UserDao userdao = new UserDao();
			users = userdao.getUserByUnitId( ((Unit)units.get(0)).getUnitid() );
		}
		Iterator it = users.iterator();
		String json = "([";
		while(it.hasNext())
		{
			json += "\""+((Users)it.next()).getUsername()+"\",";
		}
		json += "])";
		out.print(json);
		out.flush();
		out.close();
	}

	

}
